package com.linjuke.mayouting.biz.bo.biz.impl;

import java.awt.image.BufferedImage;
import java.io.OutputStream;

import org.apache.avalon.framework.configuration.DefaultConfiguration;
import org.krysalis.barcode4j.BarcodeGenerator;
import org.krysalis.barcode4j.BarcodeUtil;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import org.krysalis.barcode4j.tools.MimeTypes;

import com.linjuke.mayouting.biz.bo.biz.BarCodeService;

public class BarCode4jService implements BarCodeService {
	
	private static final String FORMAT = MimeTypes.MIME_JPEG;
	
	private static final int ORIENTATION = 0;
	
	private static final int RESOLUTION = 300;
	
	private static final String BARCODE_TYPE = "datamatrix";
	
	public void genBarCode(OutputStream os, String msg) {
		DefaultConfiguration configuration = new DefaultConfiguration("barcode");
		DefaultConfiguration child = new DefaultConfiguration(BARCODE_TYPE);
		configuration.addChild(child);
		DefaultConfiguration attr = new DefaultConfiguration("height");
		attr.setValue(50);
		child.addChild(attr);
		attr = new DefaultConfiguration("module-width");
		attr.setValue("0.5");
		child.addChild(attr);

		BitmapCanvasProvider bitmap = null;
		try {
			BarcodeUtil util = BarcodeUtil.getInstance();
			BarcodeGenerator gen = util.createBarcodeGenerator(configuration);
			bitmap = new BitmapCanvasProvider(os, FORMAT, RESOLUTION, BufferedImage.TYPE_BYTE_GRAY, true, ORIENTATION);
			gen.generateBarcode(bitmap, msg);
			bitmap.finish();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}
